package com.alks.function.service.impl.finance.mtlcosts;

import com.alibaba.excel.util.StringUtils;
import com.alks.common.aop.AutoPageAop;
import com.alks.common.data.dto.SysUserTokenDTO;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.service.RedisService;
import com.alks.common.utils.DatabaseUtils.DatabaseUtils;
import com.alks.common.utils.beanutils.ArrayUtils;
import com.alks.common.utils.beanutils.BeanUtil;
import com.alks.common.utils.number.AmtUtils;
import com.alks.entity.data.entity.PcCostDetail;
import com.alks.entity.data.entity.PcCostTemp;
import com.alks.entity.data.entity.PcLotHead;
import com.alks.entity.data.entity.YfCostDetail;
import com.alks.entity.data.enums.CompanyEnum;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.controller.task.FinanceFinconsTask;
import com.alks.function.data.dto.finance.ryfinance.CostDetailDto;
import com.alks.function.data.request.finance.ryfinance.CostDTTRequest;
import com.alks.function.data.request.finance.ryfinance.CostDetUpRequest;
import com.alks.function.data.request.finance.ryfinance.CostDetailQueryRequest;
import com.alks.function.data.request.finance.ryfinance.CostTempToDetailRequest;
import com.alks.function.mapper.SdDepartmentMapper;
import com.alks.function.mapper.chengKong.PcLotHeadMapper;
import com.alks.function.mapper.common.BackMapper;
import com.alks.function.mapper.finance.mtlcosts.PcCostDetailMapper;
import com.alks.function.mapper.finance.ryfinance.PcCostTempMapper;
import com.alks.function.service.finance.mtlcosts.IMcBillFessService;
import com.alks.function.service.impl.finance.ryfinance.BillFessServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static com.alks.common.utils.DateUtils.financeYymmCheck;
import static com.alks.common.utils.beanutils.StringUtils.convertToUpper;
import static com.alks.entity.data.enums.RedisKeyEnum.COST_DETAIL2;

/**
 * @author MS
 * @since 2024/6/7上午10:05
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class McBillFessServiceImpl extends ServiceImpl<PcCostTempMapper, PcCostTemp> implements IMcBillFessService {
    private final PcCostDetailMapper detailMapper;
    private final SdDepartmentMapper deptMapper;
    private final PcCostTempMapper tempMapper;
    private final BackMapper backMapper;
    private final RedisService redisService;
    private final PcLotHeadMapper lotHeadMapper;
    private final BillFessServiceImpl fessService;
    private final FinanceFinconsTask financeFinconsTask;

    private final String RsDeptName = "荣信研发";
    private final String RsAccName = "荣信";
    private final String RyDeptName = "荣阳车间";
    private final String RyAccName = "荣阳大货";
    private final String kk = "扣款";

    @Override
    @AutoPageAop
    public Map<String, Object> costDetailQuery(CostDetailQueryRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        final int asc = 1;
        final int desc = 2;
        DatabaseUtils.sqlCheck(request.getOrderName());
        /*获取页数*/
        List<CostDetailDto> dtos = detailMapper.costDetailQuery(request,companyId);
        /*封装数据*/
        Map<String, Object> map = new HashMap<>(4);
        /*计算求和数据*/
        List<PcCostDetail> details1 = detailMapper.costDetailSumQuery(request,companyId);
        BigDecimal amtSum = details1.stream()
                .filter(Objects::nonNull)
                .map(PcCostDetail::getAmt)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal qtySum = details1.stream()
                .filter(Objects::nonNull)
                .map(PcCostDetail::getQty)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        map.put("dtos", dtos);
        map.put("amtSum", AmtUtils.formatWithUnit(amtSum,true));
        map.put("qtySum", AmtUtils.formatWithUnit(qtySum,true));
        if (!request.getPageNum().equals(-1)&&!request.getPageSize().equals(-1)) {
            Page<CostDetailDto> page = (Page<CostDetailDto>) dtos;
            map.put("total", page.getTotal());
        }
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseInfo costTempToDetail(CostTempToDetailRequest request) {
        String kk = "扣款";
        SysUserTokenDTO tokenDTO = UserIdThread.get();
        String companyId = tokenDTO.getCompanyId();
        String loginName = tokenDTO.getLoginName();
        /*入参判断*/
        String vendorNo = backMapper.getVendorNoByName(request.getVendorName());
        request.setVendorNo(vendorNo);
        toDetailReqBlankCheck(request);
        List<Map<String, String>> costType = backMapper.getPcCostType(null, request.getTypeName(), companyId);
        if (ArrayUtils.isEmpyt(costType)) {
            return ResponseInfo.error("费用类型不存在");
        } else {
            request.setTypeNo(costType.get(0).get("typeNo"));
        }
        /*获取要写入的数据*/
        LambdaQueryWrapper<PcCostTemp> wrapper = new LambdaQueryWrapper<PcCostTemp>()
                .eq(PcCostTemp::getCompanyId, companyId)
                .eq(PcCostTemp::getSysUser, loginName);
        List<PcCostTemp> temps = tempMapper.selectList(wrapper);
        if (ArrayUtils.isEmpyt(temps)){
            throw new ServiceErrorException("费用明细为空");
        }
        /*扣款金额单价不能大于0*/
        if (kk.equals(request.getTypeName())){
            List<PcCostTemp> collect = temps.stream()
                    .filter(a -> a.getAmt().compareTo(BigDecimal.ZERO) > 0)
                    .collect(Collectors.toList());
            if (ArrayUtils.isNoEmpyt(collect)){
                throw new ServiceErrorException("扣款金额不能大于零");
            }
        }
        List<PcCostDetail> details = BeanUtil.copyList(temps, PcCostDetail.class);
        /*获取最终的slipNo(含有修改则用旧数据 没有则新建slipNo)*/
        String slipNo = temps.stream()
                .filter(a -> "修改".equals(a.getFeeStatus()))
                .map(PcCostTemp::getFeeSlipNo).findAny()
                .orElse(redisService.slipNoCreat(COST_DETAIL2.getKey()));
        /*扣款处理*/
        List<PcCostTemp> cbTemps = temps.stream().filter(a -> kk.equals(a.getFeeStatus())).collect(Collectors.toList());
        if (ArrayUtils.isNoEmpyt(cbTemps)) {
            Map<BigDecimal, String> cbSlipNoMap = cbTemps.stream()
                    .collect(Collectors.toMap(PcCostTemp::getItem, a -> a.getFeeSlipNo() + "_" + a.getFeeItem()));
            for (PcCostDetail detail : details) {
                /*写入扣款记录*/
                if (cbSlipNoMap.containsKey(detail.getItem())) {
                    String[] split = cbSlipNoMap.get(detail.getItem()).split("_");
                    detail.setCbSlipNo(split[0]);
                    detail.setCbItem(new BigDecimal(split[1]));
                }
            }
        }
        /*写入detail数据*/
        for (PcCostDetail detail : details) {
            detail.setSlipNo(slipNo);
            detail.setSysDate(LocalDateTime.now());
            detail.setSlipDate(request.getSlipDate());
            detail.setSysUser(loginName);
            detail.setDeptNo(request.getDeptNo());
            detail.setVendorName(request.getVendorName());
            detail.setTypeName(request.getTypeName());
            detail.setAccountName(request.getAccountName());
            detail.setSendNo(request.getSendNo());
            detailMapper.insert(detail);
        }
        /*删除temp数据*/
        tempMapper.delete(wrapper);
        /*写入补单扣款项*/
        List<PcCostDetail> kkDetails = details.stream().filter(a -> StringUtils.isNotBlank(a.getCbSlipNo())).collect(Collectors.toList());
        if (ArrayUtils.isNoEmpyt(kkDetails)) {
            for (PcCostDetail kkDetail : kkDetails) {
                LambdaUpdateWrapper<PcCostDetail> costDetailWrapper = new LambdaUpdateWrapper<PcCostDetail>()
                        .eq(PcCostDetail::getCompanyId,companyId)
                        .eq(PcCostDetail::getSlipNo, kkDetail.getCbSlipNo())
                        .eq(PcCostDetail::getItem, kkDetail.getCbItem())
                        .set(PcCostDetail::getProcessStatus,kk);
                detailMapper.update(null,costDetailWrapper);
            }
        }

        return ResponseInfo.ok();
    }

    /**
     * 增加功能的入参空值检测
     *
     * @param request 入参
     */
    private void toDetailReqBlankCheck(CostTempToDetailRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        if (request.getSlipDate() == null) {
            throw new ServiceErrorException("单据日期不能为空");
        }
        if (StringUtils.isBlank(request.getVendorName())) {
            throw new ServiceErrorException("厂商不能为空");
        }
        if (StringUtils.isBlank(request.getTypeName())) {
            throw new ServiceErrorException("费用类型不能为空");
        }
        if (StringUtils.isBlank(request.getVendorNo())) {
            throw new ServiceErrorException("厂商不能为空");
        }
        if (StringUtils.isBlank(request.getAccountName())) {
            if (CompanyEnum.RY.getOldId().equals(companyId)){
                request.setAccountName(RyAccName);
            }else if (CompanyEnum.RS.getOldId().equals(companyId)){
                request.setAccountName(RsAccName);
            }
        }
        if (StringUtils.isBlank(request.getDeptNo())) {
            if (CompanyEnum.RY.getOldId().equals(companyId)){
                request.setDeptNo(RyDeptName);
            }else if (CompanyEnum.RS.getOldId().equals(companyId)){
                request.setDeptNo(RsDeptName);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseInfo costDetailToTemp(List<CostDTTRequest> request, Integer type) {
        SysUserTokenDTO tokenDTO = UserIdThread.get();
        String loginName = tokenDTO.getLoginName();
        String companyId = tokenDTO.getCompanyId();
        /*获取detail数据*/
        List<PcCostTemp> temps;
        if (type.equals(1)) {
            /*处理修改情况*/
            temps = modifyQuery(request, loginName, companyId);
        } else {
            /*处理扣款情况*/
            temps = chargeBackQuery(request, loginName, companyId);
        }
        /*写入数据*/
        if (!ArrayUtils.isEmpyt(temps)) {
            temps.forEach(tempMapper::insert);
        } else {
            log.warn("\n异常接口：costDetailToTemp\n异常原因：没有找到数据\n表名：【PC_COST_DETAIL】 传参:{}", request);
            throw new ServiceErrorException("数据异常");
        }
        return ResponseInfo.ok();
    }

    /**
     * 修改按钮对应获取数据修改和查询
     *
     * @param request   传入数据
     * @param loginName 用户英文名
     * @param companyId 公司ID
     * @return temps
     */
    @Transactional(rollbackFor = Exception.class)
    @NotNull
    public List<PcCostTemp> modifyQuery(List<CostDTTRequest> request, String loginName, String companyId) {
        /*判断是否有扣款*/
        for (CostDTTRequest r : request) {
            chargeBackCheck(r.getSlipNo(), r.getItem());
        }
        List<PcCostTemp> temps;
        /*获取需要的数据*/
        List<String> slipNoList = request.stream()
                .map(CostDTTRequest::getSlipNo)
                .collect(Collectors.toList());
        temps = detailMapper.modifyQuery(request, loginName, companyId);
        /*判断是否已检核*/
        LambdaQueryWrapper<PcCostDetail> detailWrapper = new LambdaQueryWrapper<PcCostDetail>()
                .eq(PcCostDetail::getCompanyId, companyId)
                .in(PcCostDetail::getSlipNo, slipNoList);
        List<PcCostDetail> details = detailMapper.selectList(detailWrapper);
        List<PcCostDetail> cfmList = details.stream()
                .filter(a -> StringUtils.isNotBlank(a.getCfmFlag()) &&
                        "Y".equals(a.getCfmFlag()))
                .collect(Collectors.toList());
        if (ArrayUtils.isNoEmpyt(cfmList)){
            throw new ServiceErrorException("订单"+cfmList.get(0).getSlipNo()+"已检核");
        }
        /*写入序号*/
        AtomicInteger counter = new AtomicInteger(0);
        temps.forEach(temp -> temp.setItem(BigDecimal.valueOf(counter.getAndIncrement())));
        /*修改需要删除以前的数据*/
        LambdaQueryWrapper<PcCostTemp> tempWrapper = new LambdaQueryWrapper<PcCostTemp>()
                .eq(PcCostTemp::getSysUser, loginName)
                .eq(PcCostTemp::getCompanyId, companyId);
        /*处理扣款项*/
        List<PcCostTemp> temps1 = tempMapper.selectList(tempWrapper);
        if (ArrayUtils.isNoEmpyt(temps1)) {
            temps1.forEach(temp -> {
                if (kk.equals(temp.getFeeStatus())) {
                    statusCancel(companyId, temp.getFeeSlipNo(), temp.getFeeItem());
                }
            });
        }
        /*删除两张表里的数据*/
        detailMapper.delete(detailWrapper);
        tempMapper.delete(tempWrapper);
        return temps;
    }

    /**
     * 处理扣款情况的数据修改和查询
     *
     * @param request   定位数据
     * @param loginName 用户英文名
     * @param companyId 公司ID
     * @return 待写入数据
     */
    @Transactional(rollbackFor = Exception.class)
    @NotNull
    public List<PcCostTemp> chargeBackQuery(List<CostDTTRequest> request, String loginName, String companyId) {
        List<PcCostTemp> temps;
        /*获取数据*/
        temps = detailMapper.chargeBackQuery(request, loginName, companyId);
        /*获取序号并写入*/
        BigDecimal itemMax = lambdaQuery()
                .select(PcCostTemp::getItem)
                .eq(PcCostTemp::getCompanyId, companyId)
                .eq(PcCostTemp::getSysUser, loginName).list()
                .stream().map(PcCostTemp::getItem)
                .max(BigDecimal::compareTo)
                .orElse(BigDecimal.ZERO)
                .add(BigDecimal.ONE);
        for (PcCostTemp temp : temps) {
            temp.setItem(itemMax);
            itemMax = itemMax.add(BigDecimal.ONE);
        }
        return temps;
    }


    @Override
    public ResponseInfo costDetailUpdate(List<CostDetUpRequest> request, Integer financeType, String financeYymm) {
        SysUserTokenDTO tokenDTO = UserIdThread.get();
        String userName = tokenDTO.getUserName();
        String companyId = tokenDTO.getCompanyId();
        if (financeType!=null && financeType == 1) {
            financeYymmCheck(financeYymm);
        }
        /*获取基础数据*/
        List<PcCostDetail> details = detailMapper.costDetUpDateQuery(request, companyId);
        /*判断是否有已应付*/
        if(financeType!=null&& financeType != 3) {
            List<PcCostDetail> balanceList = details.stream().filter(a -> StringUtils.isNotBlank(a.getBalanceNo())).collect(Collectors.toList());
            if (ArrayUtils.isNoEmpyt(balanceList)) {
                String balanceSlipNo = balanceList.get(0).getSlipNo();
                throw new ServiceErrorException("单据号" + balanceSlipNo + "已应付，不能取消结算");
            }
        }
        /*判断是否重复检核*/
        if (financeType!=null && financeType == 1) {
            List<PcCostDetail> finList = details.stream()
                    .filter(a -> StringUtils.isNotBlank(a.getCfmFlag()))
                    .collect(Collectors.toList());
            if (ArrayUtils.isNoEmpyt(finList)) {
                String slipNo = finList.get(0).getSlipNo();
                throw new ServiceErrorException("单据号" + slipNo + "已结算，请勿重复结算");
            }
            detailMapper.costDetCheck(request, financeYymm, userName, companyId);
        } else if (financeType!=null && financeType == 2) {
            List<PcCostDetail> unFinList = details.stream()
                    .filter(a -> StringUtils.isBlank(a.getCfmFlag()))
                    .collect(Collectors.toList());
            if (ArrayUtils.isNoEmpyt(unFinList)) {
                String slipNo = unFinList.get(0).getSlipNo();
                throw new ServiceErrorException("单据号" + slipNo + "未结算，不能取消结算");
            }
            detailMapper.costDetUnCheck(request, companyId);
        }
        detailMapper.cwRekUp(request, companyId);
        /*数据检核*/
        return ResponseInfo.ok();
    }

    /**
     * 取消结算处理
     *
     * @param wrapper 数据定位
     */
    private void cancelFinance(LambdaUpdateWrapper<PcCostDetail> wrapper) {
        /*检测是否存在未结算*/
        List<PcCostDetail> details = detailMapper.selectList(wrapper);
        for (PcCostDetail detail : details) {
            if (detail.getCfmFlag() == null || !"Y".equals(detail.getCfmFlag())) {
                log.warn("\n异常接口：costDetailUpdate\n异常原因：取消结算了未结算的数据\n对应数据：{}", detail);
                throw new ServiceErrorException("存在未结算数据，单据号码：" + detail.getSlipNo());
            }
            if (detail.getBalanceNo() != null) {
                log.warn("\n异常接口：costDetailUpdate\n异常原因：取消结算了已应付的数据\n对应数据：{}", detail);
                throw new ServiceErrorException("存在已应付数据，单据号码：" + detail.getSlipNo());
            }
        }
        /*补充数据修改*/
        wrapper.set(PcCostDetail::getFinanceYymm, null)
                .set(PcCostDetail::getCfmFlag, null)
                .set(PcCostDetail::getCfmUser, null)
                .set(PcCostDetail::getCfmDate, null);
    }


    /**
     * 结算处理
     *
     * @param financeYymm 结算年月
     * @param wrapper     定位数据
     * @param userName    操作人
     */
    private void finance(String financeYymm, LambdaUpdateWrapper<PcCostDetail> wrapper, String userName) {
        /*检核月份输入是否正确*/
        ResponseInfo<Object> info = DatabaseUtils.financeDateCheck(financeYymm);
        if (info != null) {
            throw new ServiceErrorException((String) info.getMessage());
        }
        /*检测是否存在已结算*/
        List<PcCostDetail> details = detailMapper.selectList(wrapper);
        for (PcCostDetail detail : details) {
            if (detail.getCfmFlag() != null && "Y".equals(detail.getCfmFlag())) {
                log.warn("\n异常接口：costDetailUpdate\n异常原因：结算了已经结算的数据\n对应数据：{}", detail);
                throw new ServiceErrorException("存在已结算数据，单据号码：" + detail.getSlipNo());
            }
        }
        /*补充数据修改*/
        wrapper.set(PcCostDetail::getFinanceYymm, financeYymm)
                .set(PcCostDetail::getCfmFlag, "Y")
                .set(PcCostDetail::getCfmUser, userName)
                .set(PcCostDetail::getCfmDate, LocalDate.now());
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseInfo costDetailDelete(List<Integer> idList) {
        SysUserTokenDTO tokenDTO = UserIdThread.get();
        String companyId = tokenDTO.getCompanyId();
        for (Integer i : idList) {
            /*判断是否结算*/
            PcCostDetail detail = detailMapper.selectById(i);
            if (detail==null){
                log.error("\n错误接口：costDetailDelete\n错误原因：未查询到指定数据\n表【PC_COST_DETAIL】");
                throw new ServiceErrorException("数据异常");
            }if (detail.getCfmFlag() != null && "Y".equals(detail.getCfmFlag())){
                throw new ServiceErrorException(detail.getSendNo()+"已结算，不能删除");
            }
            /*检查是否存在扣款*/
            chargeBackCheck(detail.getSlipNo(),detail.getItem());
            statusCancel(companyId,detail.getSlipNo(),detail.getItem());
            /*删除数据*/
            detailMapper.deleteById(i);
        }
        return ResponseInfo.ok();
    }

    /**
     * 去除扣款标志
     * @param slipNo 待去扣款标志订单号
     * @param item 待去扣款标志订单内序号
     */
    private void statusCancel(String companyId, String slipNo, BigDecimal item) {
        /*检测是否还有其他扣款项*/
        LambdaQueryWrapper<PcCostDetail> detailWrapper = new LambdaQueryWrapper<PcCostDetail>()
                .eq(PcCostDetail::getCompanyId, companyId)
                .eq(PcCostDetail::getCbSlipNo, slipNo)
                .eq(PcCostDetail::getCbItem, item);
        if (detailMapper.selectCount(detailWrapper).equals(0)) {
            /*如果没有则删除扣款标志*/
            LambdaUpdateWrapper<PcCostDetail> detailUpWrapper = new LambdaUpdateWrapper<PcCostDetail>()
                    .set(PcCostDetail::getProcessStatus, null)
                    .eq(PcCostDetail::getCompanyId, companyId)
                    .eq(PcCostDetail::getSlipNo, slipNo)
                    .eq(PcCostDetail::getItem, item);
            detailMapper.update(null, detailUpWrapper);
        }
    }

    @Override
    public void costTempAdd(PcCostTemp request) {
        SysUserTokenDTO tokenDTO = UserIdThread.get();
        String companyId = tokenDTO.getCompanyId();
        String loginName = tokenDTO.getLoginName();
        /*判断指令是否存在*/
        /*12.17 费用可以不携带指令*/
        if (StringUtils.isNotBlank(request.getLotNo())) {
            LambdaQueryWrapper<PcLotHead> ordWrapper = new LambdaQueryWrapper<PcLotHead>()
                    .eq(PcLotHead::getCompanyId, companyId)
                    .eq(PcLotHead::getLotNo, request.getLotNo());
            if (lotHeadMapper.selectCount(ordWrapper) <= 0) {
                log.error("\n错误接口：costTempAdd\n错误原因：尝试写入不存在的指令：{}", request.getLotNo());
                throw new ServiceErrorException("指令不存在");
            }
        }
        /*获取item*/
        List<PcCostTemp> temps = lambdaQuery()
                .eq(PcCostTemp::getCompanyId, companyId)
                .eq(PcCostTemp::getSysUser, loginName).list();
        BigDecimal item = temps.stream()
                .map(PcCostTemp::getItem)
                .filter(Objects::nonNull)
                .reduce((max, current) -> (max.compareTo(current) >= 0) ? max : current)
                .map(max -> max.add(BigDecimal.ONE))
                /*设置默认值为1*/
                .orElse(BigDecimal.ZERO.add(BigDecimal.ONE));
        request.setCompanyId(companyId);
        request.setItem(item);
        request.setSysUser(loginName);
        /*写入数据*/
        tempMapper.insert(request);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void costInsert(List<PcCostDetail> detailList) {
        SysUserTokenDTO tokenDTO = UserIdThread.get();
        String companyId = tokenDTO.getCompanyId();
        String userId = tokenDTO.getUserId();
        String slipNo = redisService.slipNoCreat("F");
        BigDecimal item = BigDecimal.ZERO;
        for (PcCostDetail detail : detailList) {
            CostTempToDetailRequest request = BeanUtil.copyBean(detail, CostTempToDetailRequest.class);
            List<Map<String, String>> costType = backMapper.getPcCostType(null, detail.getTypeName(), companyId);
            if (ArrayUtils.isEmpyt(costType)) {
                throw new ServiceErrorException("费用类型不存在");
            } else {
                detail.setTypeNo(costType.get(0).get("typeNo"));
            }if ("扣款".equals(detail.getTypeName())&&detail.getAmt().compareTo(BigDecimal.ZERO)>0){
                throw new ServiceErrorException("存在扣款金额大于0");
            }
            toDetailReqBlankCheck(request);
            detail.setItem(item);
            detail.setDeptNo(request.getDeptNo());
            detail.setAccountName(request.getAccountName());
            detail.setSysDate(LocalDateTime.now());
            detail.setSlipNo(slipNo);
            detail.setCompanyId(companyId);
            detail.setSysUser(userId);
            detailMapper.insert(detail);
            item = item.add(BigDecimal.ONE);
        }
    }

    @Override
    public ResponseInfo costTempDelete(Integer item) {
        SysUserTokenDTO tokenDTO = UserIdThread.get();
        String companyId = tokenDTO.getCompanyId();
        String loginName = tokenDTO.getLoginName();
        /*删除数据*/
        LambdaQueryWrapper<PcCostTemp> wrapper = new LambdaQueryWrapper<PcCostTemp>()
                .eq(PcCostTemp::getCompanyId, companyId)
                .eq(PcCostTemp::getSysUser, loginName)
                .eq(PcCostTemp::getItem, item);
        PcCostTemp pcCostTemp = tempMapper.selectOne(wrapper);
        /*处理扣款事件*/
        if (pcCostTemp != null && kk.equals(pcCostTemp.getFeeStatus())){
            statusCancel(companyId, pcCostTemp.getFeeSlipNo(),pcCostTemp.getFeeItem());
        }
        tempMapper.delete(wrapper);
        return ResponseInfo.ok();
    }

    /**
     * 检测是否存在扣款
     * @param slipNo 单据号
     */
    private void chargeBackCheck(String slipNo, BigDecimal item) {
        String status = "扣款";
        /*处理为备注*/
        String companyId = UserIdThread.get().getCompanyId();
        LambdaQueryWrapper<PcCostDetail> wrapper = new LambdaQueryWrapper<PcCostDetail>()
                .eq(PcCostDetail::getCbSlipNo, slipNo)
                .eq(PcCostDetail::getCbItem, item)
                .eq(PcCostDetail::getCompanyId, companyId);
        if (detailMapper.selectCount(wrapper) > 0) {
            throw new ServiceErrorException("存在扣款记录");
        }
    }
}
